import redis
from threading import Lock


class RedisSingleton:
    _instance = None
    _lock = Lock()

    def __new__(cls, *args, **kwargs):
        # 确保 Redis 连接池实例是单例
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super(RedisSingleton, cls).__new__(cls, *args, **kwargs)
                    cls._instance._initialize_redis()
        return cls._instance

    def _initialize_redis(self):
        # 从 Flask 的配置加载 Redis 连接池参数
        from flask import current_app

        # 获取配置
        self.redis_pool = redis.ConnectionPool(
            host=current_app.config.get('REDIS_HOST'),
            port=current_app.config.get('REDIS_PORT'),
            max_connections=current_app.config.get('REDIS_MAX_CONNECTIONS', 10),
            decode_responses=True  # 返回的字符串会自动解码为 UTF-8
        )

    def get_pool(self):
        # 返回 Redis 连接池
        return self.redis_pool

    def get_redis(self):
        # 获取 Redis 客户端
        return redis.Redis(connection_pool=self.redis_pool, decode_responses=True)


# # 创建 Redis 连接池
# common_redis_pool = util.ConnectionPool(
#     host='127.0.0.1',     # Redis 服务器地址
#     port=6378,            # Redis 端口
#     max_connections=10,    # 最大连接数
#     decode_responses=True
# )
#
# common_redis_client = util.Redis(connection_pool=common_redis_pool, decode_responses=True)
